{us/mf/mfdtitle.i}
{us/px/pxmaint.i}
{us/px/pxphdef.i ppprxr}
{xxjson.i}
{xxcimload.i}
 
&GLOBAL-DEFINE APMATCHINGSTATUS-INITIAL 'INITIALAPMATCHING'
&GLOBAL-DEFINE APMATCHINGSTATUS-CANCEL 'CANCEL'



define input parameter vc_inputjson             as character format "x(60)" no-undo.
define input parameter vc_outputjson            as character format "x(60)" no-undo.
define input parameter vc_import                as logical  no-undo.


DEFINE VARIABLE li_access           AS    INTEGER                       NO-UNDO.
define variable l_file                       as character format "x(40)" no-undo.
define variable l_line                       as character   no-undo.
define variable lvi_row_id                   as decimal     no-undo.
define variable v_import                     as logical     init   "no"      no-undo.
define variable v_site                       like si_site   no-undo.

define variable l_error                      as character      no-undo.
define stream f_log.
define stream f_cim.
define variable v_quote               as character initial """"   no-undo.
define variable v_default             as character initial "-"    no-undo.
define variable v_space               as character initial " "    no-undo.
define variable v_log                 as character                no-undo.
define variable v_cim                 as character                no-undo.
define variable v_fline               as character                no-undo.
define variable v_errorstatus         as logical                  no-undo.
define variable v_toterrorstatus      as logical initial yes      no-undo.
define variable v_errstring           as character                no-undo.
define variable v_status              as character                no-undo.

define variable v_entity              like si_entity              no-undo.
define variable v_ee                  as logic                    no-undo.

define variable vi_filecount          as integer                  no-undo.
define variable vc_filename           as character                no-undo.
define variable vc_topath             as character                no-undo.
define variable v_runproagram        as character                no-undo.
define variable vc_traceid            as character                no-undo.


 define temp-table ttSearchCondition no-undo
        field supplier_from         like Debtor.DebtorCode
        field supplier_to           like Debtor.DebtorCode
        field site_from             like si_mstr.si_site
        field site_to               like si_mstr.si_site
        field date_from             as date
        field effective_date         as date 
        .

 
define variable vendor     like po_vend no-undo.
define variable vendor1    like po_vend no-undo.
define variable part       like pt_part no-undo.
define variable part1      like pt_part no-undo.
define variable site       like pt_site no-undo.
define variable site1      like pt_site no-undo.
define variable acc        like ap_acct no-undo.
define variable acc1       like ap_acct no-undo.
define variable sub        like ap_sub no-undo.
define variable sub1       like ap_sub no-undo.
define variable cc         like ap_cc no-undo.
define variable cc1        like ap_cc no-undo.
define variable effdate    like prh_rcp_date format "99/99/99" no-undo.
define variable rcpt_from  like prh_rcp_date format "99/99/99" no-undo.
define variable sel_inv    like mfc_logical  initial yes no-undo.
define variable sel_sub    like mfc_logical  initial yes no-undo.
define variable sel_mem    like mfc_logical  initial yes no-undo.
define variable use_tot    like mfc_logical  initial no no-undo.
define variable base_rpt   like po_curr no-undo.
define variable l-summary  like mfc_logical no-undo.
define variable rndmthd    like rnd_rnd_mthd no-undo.
define variable oldcurr    like prh_curr no-undo.
define variable std_ext    as decimal format "->>>>>>>>>>9.99<<<" no-undo.
define variable pur_ext    as decimal format "->>>>>>>>>>9.99<<<" no-undo.
define variable tax_accrued as decimal format "->>>>>>>>>>9.99<<<" no-undo.
define variable openTaxAmount    like tx2d_totamt no-undo.
define variable rep_tot_with_tax as decimal format "->>>>>>>>>>9.99<<<" no-undo.
define variable std_cost   as decimal format "->>>>>>>9.99<<<" no-undo.
define variable std_var    as decimal format "->>>>>>>9.99<<<" no-undo.
define variable base_cost  as decimal format "->>>>>>>>9.99<<<" no-undo.
define variable disp_curr  as character format "X(1)" no-undo.
define variable descname   as character format "x(50)" no-undo.
define variable total_prh_qty_open  as decimal
                           format "->>>>>>9.9<<<<<<"  no-undo.
define variable report_qty_open as decimal   format "->>>>>>9.9<<<<<<"  no-undo.
define variable exdrate    like ap_ex_rate no-undo.
define variable last_nbr   like prh_nbr no-undo.
define variable last_vend  like prh_vend no-undo.
define variable base_std_cost as decimal no-undo.
define variable rcptacct   like ap_acct no-undo.
define variable rcptsub    like ap_sub no-undo.
define variable rcptcc     like ap_cc no-undo.
define variable rcptxacct  like ap_acct no-undo.
define variable rcptxsub   like ap_sub no-undo.
define variable rcptxcc    like ap_cc no-undo.
define variable receiptacc like ap_acct no-undo.
define variable receiptsub like ap_sub no-undo.
define variable receiptcc  like ap_cc no-undo.
define variable qty_vph    like total_prh_qty_open no-undo.
define variable vendor_type like vd_type no-undo.
define variable mc-error-number  like msg_nbr no-undo.
define variable excl_unconfirmed like mfc_logical initial yes no-undo.
define variable eff_date   like prh_rcp_date no-undo.
define variable l_APMatchingLnMatchQty     as decimal   format "->>>>>>9.9<<<<<<"  no-undo.
define variable l_APMatchingLnReceiptTaxLC like tx2d_totamt no-undo.

define variable ext_amt_fmt     as character format "x(20)" no-undo.
define variable summary_tot_fmt as character format "x(20)" no-undo.
define variable var_cost_fmt    as character format "x(15)" no-undo.
define variable l_rndmthd       like rnd_rnd_mthd no-undo.
define variable l_tt_pur_ext_tot as decimal format "->>,>>>,>>>,>>9.99"
                                         initial 0 no-undo.								 


define temp-table ttprhhist no-undo

            field prh_domain     like prh_hist.prh_domain  
            field prh_entity     like si_entity
            field prh_orginalrc  like prh_hist.prh_receiver     
            field prh_receiver   like prh_hist.prh_receiver
            field prh_vend       like prh_hist.prh_vend    
            field prh_ps_nbr     like prh_hist.prh_ps_nbr  
            field prh_nbr        like prh_hist.prh_nbr     
            field prh_rcp_date   like prh_hist.prh_rcp_date
            field prh_line       like prh_hist.prh_line    
            field prh_rcvd       like prh_hist.prh_rcvd    
            field prh_qty_open   like prh_hist.prh_rcvd    
            field prh_rc_type    as   character  
            field prh_part       like prh_hist.prh_part    
            field prh_site       like prh_hist.prh_site    
            field prh_reason     as   character  
            field prh_um         like prh_hist.prh_um      
            field prh_loc        like tr_loc  
            field prh_curr       like prh_hist.prh_curr
            field prh_curr_amt    like    prh_hist.prh_curr_amt
            field prh_ex_rate     like   prh_hist.prh_ex_rate
            field prh_ex_rate2    like    prh_hist.prh_ex_rate2
            field prh_ex_ratetype like       prh_hist.prh_ex_ratetype
            field prh_lot         like   prh_hist.prh_lot 
            field prh_po_site     like   prh_hist.prh_po_site
            field prh_pur_cost    like    prh_hist.prh_pur_cost
            field prh_pur_std     like   prh_hist.prh_pur_std
            field prh_rcp_type    like    prh_hist.prh_rcp_type
            field prh_request     like   prh_hist.prh_request
            field prh_ship        like   prh_hist.prh_ship 
            field prh_tax_env     like    prh_hist.prh_tax_env 
            field prh_tax_in      like    prh_hist.prh_tax_in
            field prh_tax_usage   like      prh_hist.prh_tax_usage 
            field prh_taxc        like    prh_hist.prh_taxc 
            field prh_type        like   prh_hist.prh_type
            field prh_um_conv     like   prh_hist.prh_um_conv
            field prh_tx2_tax_pct like       tx2_mstr.tx2_tax_pct
            field prh_status as      character
            

            field prh_traceid    as   character  
            field prh_dataid     as   character                 
                             
            index prhtraceid prh_traceid
            index prh1 prh_domain prh_receiver prh_line prh_site
            index prh3 prh_receiver
            index prh4 prh_ps_nbr.

     
           
      
            DEFINE DATASET dsSearchCondition FOR ttSearchCondition.

            hdataset = dataset dsSearchCondition:HANDLE.   
                    
            DEFINE DATASET dsGrir FOR ttprhhist.
         
            hresult = dataset dsGrir:HANDLE.    
                         
                							 
										 
/* QAD Financials API DEFINITIONS */
define variable hQADFinancialsLib as handle no-undo.
{proxy/bapmatching/apigetmatchinginfomultidef.i}

 
{us/ap/apconsdf.i}
{us/po/popvodet.i}   /* pvod_det TEMP-TABLE DEFINITION */
 
define variable totalTransQty as decimal no-undo.
define variable totalTaxAccrued as decimal no-undo.
define variable pvod-trx-cost like prh_pur_cost no-undo.
define variable l_po_site  like prh_po_site no-undo.
define variable l_po_site1 like prh_po_site no-undo.
define variable l_total_qty_vph like total_prh_qty_open no-undo.
define variable l_consignment   like mfc_logical        no-undo.
for first gl_ctrl where gl_domain = global_domain no-lock: end.



  
mainloop:
    repeat on error undo mainloop, leave mainloop:

{us/xx/xxworkpath_e.i &outbound=YES &inbound=no &archive=YES}

assign m_outpath     = m_outpath + "grir/"
       m_archpath    = m_archpath + "grir/"
       m_successpath = m_successpath + "grir/"
       m_errorpath   = m_errorpath + "grir/"
       m_workpath    = m_workpath + "grir/".


        /* Load SEARCH conditions from JSON  */ 
   
   vc_outputjson = replace(vc_inputjson,".json",".run.out.json").   
   run loadjsonfile(input vc_inputjson,
                    input vc_outputjson,
                    output vl_RetOK).
                    v_errorstatus =   vl_RetOK.             
  if vl_RetOK then do:

    rcpt_from = low_date.

    for first ttSearchCondition.
	  if ttSearchCondition.site_to = "" then ttSearchCondition.site_to = hi_char.
          assign vendor = ttSearchCondition.supplier_from
                 vendor1 = ttSearchCondition.supplier_to
                
                 site =  ttSearchCondition.site_from
                 site1 =  ttSearchCondition.site_to.
          if ttSearchCondition.date_from <> ? 
          then rcpt_from = ttSearchCondition.date_from.
          if ttSearchCondition.effective_date <> ?
          then effdate = ttSearchCondition.effective_date.

     end.


     if effdate = ? then effdate = today.

     if vendor1 = "" then vendor1 = hi_char.
     if site1 = "" then site1 = hi_char.
     
  /* SET API PARAMETERS */
   assign
   icDomainCode     = global_domain
   icSupplierCodeFrom   = vendor
   icSupplierCodeTo     = vendor1
   icItemFrom           = ""
   icItemTo             = Hi_char
   itEffectiveDate      = effdate
   itReceiptsFromDate   = rcpt_from
   icSiteFrom       = site
   icSiteTo         = site1
   icPoSiteFrom     = site
   icPoSiteTo       = site1
   ilSelectInventoryItems   = yes
   ilSelectSubcontractItems = yes
   ilSelectMemoItems    = yes
   icReportCurrency     = base_rpt
   oiReturnStatus   = 0.
   
   
  empty temp-table ttprhhist.

   /* Process all receipts in the specified range */
      {proxy/bapmatching/apigetmatchinginfomultirun.i}
 
      if oiReturnStatus < 0 then do:
         /* Start qflib.p - QAD Financials Library running persistently */
         run mfairunh.p
            (input  'qflib.p',
             input  '?',
             output hQADFinancialsLib) no-error.
 
         run processErrors in hQADFinancialsLib
            (input table tFcMessages,
             input 3).
 
         return.
      end.
	   

       output to /apps/eai/work/cim/xxgrir.log.
       put unformatted vendor skip 
                       vendor1 skip 
                       site skip
                       site1 skip 
                       rcpt_from skip
                       "effdate: " effdate skip  
                       global_domain skip.

 
	  for each prh_hist no-lock
         where prh_domain = global_domain
         and (prh_vend >= vendor and prh_vend <= vendor1)
         and ((prh_rcp_date >= rcpt_from)
         or  (prh_rcp_date = ? and rcpt_from = low_date))
         and (prh_site >= site and prh_site <= site1)
		 break by prh_receiver.
         
	      assign
           total_prh_qty_open = 0
           qty_vph  = 0
           openTaxAmount = 0
           totalTransQty = 0
           l_APMatchingLnMatchQty     = 0
           l_APMatchingLnReceiptTaxLC = 0
           l_total_qty_vph = 0
           l_consignment   = no. 
		 
       for each tt_pvoddet
            where tt_pvoddet.pvod_domain = global_domain
         exclusive-lock:
            delete tt_pvoddet.
         end.
 
         /* Process all vouchers which are linked to the receiver
          * before the as of date */
         for each pvo_mstr
            where pvo_domain            = global_domain
            and   pvo_order             = prh_nbr
            and   pvo_internal_ref      = prh_receiver
            and   pvo_line              = prh_line
            and   pvo_order_type        = {&TYPE_PO}
            and   pvo_internal_ref_type = {&TYPE_POReceiver}
            and   pvo_lc_charge         = ""
         no-lock:		 
		   
		   
		  l_consignment = pvo_consignment.
            for each pvod_det
               where pvod_domain = global_domain
               and   pvod_id = pvo_id
            no-lock:
 
  
               if pvod_eff_date <= effdate
               then
                  total_prh_qty_open = total_prh_qty_open  + pvod_trans_qty.
               qty_vph = 0.
               if not can-find ( first tAPMatchingInfo
                                    where tcPvoDomain  = global_domain
                                    and   tiPvoID      = pvo_id
                                    and   tiPvodLineID = pvod_id_line)
                  and not can-find ( first vph_hist                                    
                                        where vph_domain       = global_domain          
                                        and   vph_pvo_id       = pvo_id      
                                        and   vph_pvod_id_line = pvod_id_line)
               then
                  if pvo_last_voucher <> "" then
                     qty_vph = pvod_trans_qty.
                  else
                     qty_vph = pvod_vouchered_qty.                  
               if can-find(first tAPMatchingInfo
                              where tcPvoDomain  = global_domain
                              and   tiPvoID      = pvo_id
                              and   tiPvodLineID = pvod_id_line)
               then
                  for each tAPMatchingInfo
                     where tcPvoDomain  = global_domain
                     and   tiPvoID      = pvo_id
                     and   tiPvodLineID = pvod_id_line
                  no-lock:
 
                    
                     if ttAPMatchingDate > effdate then next.
                     /* Skip the unconfirmed vouchers */
                     if excl_unconfirmed then do:
                        if tcAPMatchingStatus = {&APMATCHINGSTATUS-INITIAL} then
                           next.
                     end.
 
                     assign
                        l_APMatchingLnMatchQty     = tdAPMatchingLnMatchQty
                        l_APMatchingLnReceiptTaxLC = tdAPMatchingLnReceiptTaxLC.
 
                     if tcAPMatchingStatus = {&APMATCHINGSTATUS-CANCEL}
                     then do:
                        assign
                           l_APMatchingLnMatchQty     = 0
                           l_APMatchingLnReceiptTaxLC = 0.
                     end.
   
                     /* SET VOUCHERED QUANTITY */
                     if tAPMatchingInfo.tlAPMatchingLnIsPvodFinished and
                        pvod_cinvoice_id = tiCInvoice_ID
                     then do:
                        qty_vph = pvod_trans_qty.
                        leave.
                     end. /* IF tAPMatchingInfo.tlAPMatchingLnIsPvodFinished  */
                     else
                        qty_vph = qty_vph + l_APMatchingLnMatchQty.

                  end. /* FOR EACH tAPMatchingInfo */
               else
                  for each vph_hist 
                     where   vph_domain       = global_domain
                     and     vph_pvo_id       = pvod_det.pvod_id
                     and     vph_pvod_id_line = pvod_det.pvod_id_line
                     and     vph_inv_date     <= effdate
                  no-lock:
                     if pvo_last_voucher <> ""
                     then do:
                        qty_vph = pvod_trans_qty.
                        leave.
                     end. /* IF pvo_last_voucher <> "" */
                     else
                        qty_vph = qty_vph +  vph_inv_qty.
                  end.  /* FOR EACH vph_hist */
               /* COPY pvod_det TO TEMP-TABLE */
               {us/po/popvod.i}
               if effdate < pvod_eff_date
               then
                  pvoddet_trans_qty = 0. 
               l_total_qty_vph = l_total_qty_vph + qty_vph.
               if pvoddet_trans_qty - qty_vph = 0 then do:
                  delete tt_pvoddet.
                  next.
               end.
 
               assign
                  pvoddet_open_qty = pvoddet_trans_qty - qty_vph
                  totalTransQty    = totalTransQty + pvoddet_trans_qty
                                   - qty_vph.
 
            end. /* FOR EACH pvod_det */
         end. /* for each pvo_mstr */
 
         total_prh_qty_open = (total_prh_qty_open / prh_um_conv)
                            - (l_total_qty_vph / prh_um_conv).
 
         /* SHOULD NOT DISPLAY THE RECEIPT WHOSE QTY OPEN IS ZERO    */
		 
         if total_prh_qty_open = 0 
            and l_consignment = no
         then
            next.
          /** **/
          
 

 
         /* CALCULATE THE ACCRUED TAX */
         totalTaxAccrued = openTaxAmount * totalTransQty / prh_rcvd.
 
         for each tt_pvoddet
            where tt_pvoddet.pvod_domain = global_domain
            and   tt_pvoddet.pvoddet_open_qty <> 0
         no-lock:
   
            std_cost = pvoddet_pur_std.
 
            if prh_type = "" then
               std_cost = pvoddet_pur_std - pvoddet_ovh_std.

 
            base_std_cost = std_cost.


         /* Calculate extended GL  cost */
         assign
            eff_date        = pvoddet_eff_date
            report_qty_open = pvoddet_open_qty * prh_um_conv
            std_ext         = base_std_cost * report_qty_open.
 

 
        
        



		/* find receiver location */	 
	    find last tr_hist where tr_domain = global_domain and 
		                   tr_site   = prh_site      and
						   tr_lot    = prh_receiver  and 
                           tr_line   = prh_line      and 
						   tr_effdate = prh_rcp_date and
						   (tr_type    = "rct-po" or 
						   tr_type    = "iss-prv")   and
						   tr_part    = prh_part    no-lock no-error.
        
     
         find first tx2_mstr where tx2_mstr.tx2_domain = Global_domain
                                 and tx2_mstr.tx2_tax_type = "TAX"
                                 and tx2_mstr.tx2_pt_taxc  = prh_hist.prh_taxc
                                 and tx2_mstr.tx2_tax_usage  = prh_hist.prh_tax_usage 
                                 and tx2_mstr.tx2_effdate   <= prh_hist.prh_rcp_date
                                 and (tx2_mstr.tx2_exp_date  = ? or 
                                 tx2_mstr.tx2_exp_date >= prh_hist.prh_rcp_date)
                             no-lock no-error.

        find si_mstr where si_domain = global_domain
                       and si_site = prh_site
                       no-lock no-error .


         create ttprhhist.
         assign ttprhhist.prh_ps_nbr = prh_hist.prh_ps_nbr
                ttprhhist.prh_nbr         =                prh_hist.prh_nbr                       
                ttprhhist.prh_vend        =         prh_hist.prh_vend              
                ttprhhist.prh_entity      =             si_mstr.si_entity 
                ttprhhist.prh_receiver    =             prh_hist.prh_receiver               
                ttprhhist.prh_rcp_date    =             prh_hist.prh_rcp_date               
                ttprhhist.prh_domain      =           prh_hist.prh_domain               
                ttprhhist.prh_site        =         prh_hist.prh_site               
                ttprhhist.prh_line        =         prh_hist.prh_line               
                ttprhhist.prh_um          =       prh_hist.prh_um               
                ttprhhist.prh_part        =         prh_hist.prh_part               
                ttprhhist.prh_qty_open          =       report_qty_open               
                ttprhhist.prh_rcvd          =       prh_hist.prh_rcvd               
                ttprhhist.prh_curr        =         prh_hist.prh_curr               
                ttprhhist.prh_curr_amt    =             prh_hist.prh_curr_amt               
                ttprhhist.prh_ex_rate     =            prh_hist.prh_ex_rate               
                ttprhhist.prh_ex_rate2    =             prh_hist.prh_ex_rate2               
                ttprhhist.prh_ex_ratetype = prh_hist.prh_ex_ratetype
                ttprhhist.prh_lot         =         prh_hist.prh_lot                
                ttprhhist.prh_po_site     =            prh_hist.prh_po_site               
                ttprhhist.prh_pur_cost    =             prh_hist.prh_pur_cost               
                ttprhhist.prh_pur_std     =            prh_hist.prh_pur_std               
                ttprhhist.prh_rcp_type    =             prh_hist.prh_rcp_type               
                ttprhhist.prh_Reason      =            prh_hist.prh_Reason                
                ttprhhist.prh_request     =            prh_hist.prh_request               
                ttprhhist.prh_ship        =          prh_hist.prh_ship                
                ttprhhist.prh_tax_env     =             prh_hist.prh_tax_env                
                ttprhhist.prh_tax_in      =           prh_hist.prh_tax_in               
                ttprhhist.prh_tax_usage   =               prh_hist.prh_tax_usage                
                ttprhhist.prh_taxc        =          prh_hist.prh_taxc                
                ttprhhist.prh_type        =         prh_hist.prh_type               
                ttprhhist.prh_um_conv     =            prh_hist.prh_um_conv               
                ttprhhist.prh_tx2_tax_pct     =          tx2_mstr.tx2_tax_pct
                ttprhhist.prh_status     =          "SUCCESS"
                ttprhhist.prh_loc         =         tr_hist.tr_loc .             




 
         end. /* FOR EACH tt_pvoddet... */
      end.   /* for each prh_hist */



      end. /*   if vl_RetOK then do: */

            /* Create output json */                   
            run writejsonfile(input hresult,
            input vc_outputjson,
            input "FILE",
            input True,
            input "UTF-8",
            output vl_RetOK,
            output vc_errorstring).

      
    do vi_filecount = 1 to 5:
    /* when success move cim log file to archive directory  */
    /* when failed move cim log file to error directory  */   
    /*  move status json file to out directory for API return */   
    /* when success move previous step .p and json file to archive directory  */
    /* when failed move previous step .p and json file to error directory  */       
    case vi_filecount:
    
    when 1 then
    assign vc_filename = replace(vc_inputjson,".json",".p")
         vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
    when 2 then
    assign vc_filename = vc_inputjson
         vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
    when 3 then
    assign vc_filename = replace(vc_inputjson,".json",".dat")
         vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
    when 4 then
    assign vc_filename = replace(vc_inputjson,".json",".run.log")
         vc_topath   = m_outpath.
    when 5 then
    assign vc_filename = replace(vc_inputjson,".json",".run.out.json")
         vc_topath   =  m_outpath.
    end case.
    
    
    
    
    run cimfilehandle(input vc_filename,
                    input vc_topath,
                    input no ).                 
           
    
    
    end.       /* do vi_filecount = 1 to 5: */        

	leave.
    end. /*  mainloop */

